import gluon.contrib.simplejson as json
exec("import applications.%s.modules.apihelper as api" % request.application)

#store priority & status values in global vars
# priority_values={}
# for priority in db().select(db.priority.ALL, orderby=db.priority.sort_order):
#     priority_values[priority['id']]=priority['name']
# 
# status_values={}
# for status in db().select(db.status.ALL, orderby=db.status.sort_order):
#     status_values[status['id']]=status['name']
# 
# default_status=db().select(db.status.ALL, orderby=db.status.sort_order)[0]['name']
# default_status_id=db().select(db.status.ALL, orderby=db.status.sort_order)[0]['id']
# status_options=[OPTION(x.name, _value=x.id) for x in db().select(db.status.ALL)]
# 
# default_priority=db().select(db.priority.ALL, orderby=db.priority.sort_order)[0]['name']
# default_priority_id=db().select(db.priority.ALL, orderby=db.priority.sort_order)[0]['id']


def index(): return dict(message="hello from api.py")

def _authenticate():
    #http://unixpapa.com/auth/basic.html
    #http://en.wikipedia.org/wiki/Basic_access_authentication
    #curl http://localhost:8000/init/default/authenticate - returns none
    #curl -u user@example.com:web2py http://localhost:8000/init/api/authenticate - returns basic
    ret_dict={}
    try:
        import base64
        (uid,pwd) = (base64.decodestring(request.env.http_authorization.split(' ')[1])).split(':')
        if uid:
            from gluon.utils import md5_hash
            #users=db((db.auth_user.email==uid)&(db.auth_user.password==md5_hash(pwd))).select()
            if db((db.auth_user.email==uid)&(db.auth_user.password==md5_hash(pwd))).select():
                ret_dict=dict(uid=uid, pwd=pwd)
            else:
                ret_dict=dict(errno=1, errmsg='Authentication Failed')
    except:
        ret_dict=dict(errno=1, errmsg='Authentication Error')
    return ret_dict
        
def createcase():
    #refer: http://groups.google.com/group/web2py/browse_thread/thread/9abbaa9be66275d2
    #curl -u user@example.com:web2py http://localhost:8000/init/api/createcase/ -d fields='{"title":"this is via api","priority":1,"created_via":"curl","desc":"descriptions"}'
    
    auth_dict = _authenticate()
    if not auth_dict.has_key('uid'): return json.dumps(auth_dict)
    
    uid = db(db.auth_user.email==auth_dict['uid']).select(db.auth_user.ALL)[0]
    case_values=json.loads(request.vars.fields)
    
    try:
        case_values=json.loads(request.vars.fields)
    except:
        case_values=json.loads(eval(request.vars.fields))
    
    ret_dict={}
    try:
        api.create_case(db=db,
        title=case_values['title'] if case_values['title'] else '',
        status=api.get_default_status_id(db),
        priority=case_values['priority'] if case_values['priority'] else api.get_default_priority_id(db),
        created_via=case_values['created_via'] if case_values['created_via'] else 'API',
        desc=case_values['desc'] if case_values['desc'] else '',
        created_by=uid.id,
        created_at=request.now,
        last_modified_by=uid.id,
        last_modified_at=request.now)
        ret_dict=dict(id=0,msg='success')
    except Exception,e:
        ret_dict=dict(id=1,msg=str(e))
    return json.dumps(ret_dict)
    
def mycases():
    #curl -u user@example.com:web2py http://localhost:8000/init/api/mycases
    auth_dict = _authenticate()
    if not auth_dict.has_key('uid'): return json.dumps(auth_dict)
    uid = db(db.auth_user.email==auth_dict['uid']).select(db.auth_user.ALL)[0]
    created_by = (db.cases.created_by==uid.id)
    return json.dumps(api.get_cases(db,created_by))
    
def workitems():
    #curl -u agent1@example.com:web2py http://localhost:8000/init/api/workitems
    auth_dict = _authenticate()
    if not auth_dict.has_key('uid'): return json.dumps(auth_dict)
    uid = db(db.auth_user.email==auth_dict['uid']).select(db.auth_user.ALL)[0]
    assigned_to = (db.cases.assigned_to==uid.id)
    return json.dumps(api.get_cases(db,assigned_to))

def assign():
    #curl -u user@example.com:web2py http://localhost:8000/init/api/assign/ -d fields='{"id":16,"assign_to":"agent1@example.com"}'
    auth_dict = _authenticate()
    ret_dict={}
    if not auth_dict.has_key('uid'): return json.dumps(auth_dict)
    uid = db(db.auth_user.email==auth_dict['uid']).select(db.auth_user.ALL)[0]
    if request.vars.fields:
    	case_values=json.loads(request.vars.fields)
    	ret_dict=api.assign_case(db,case_values)
    else:
    	ret_dict={'id': 1, 'msg': 'No parameters received'}
    return json.dumps(ret_dict)	

def process_twitter():
	#this needs to have a message queue &
	#inbox & outbox; but for now, it will just be single function
	try:
		yatsy_config=db().select(db.config.ALL)
		config_id=yatsy_config[0]['id'] 
		twitter_id=yatsy_config[0]['twitter_id']
		twitter_pwd=yatsy_config[0]['twitter_pwd']
		twitter_since=yatsy_config[0]['last_twitter_intime']
		twitter_dm_id=yatsy_config[0]['last_dm_id']
		#print twitter_id, twitter_pwd, twitter_dm_id
		#all twitter msg are created in the name of user@example.com
		uid = db(db.auth_user.email=='user@example.com').select(db.auth_user.ALL)[0].id
		
		ret_dict={}
		
		exec("import applications.%s.modules.twitter as twitter" % request.application)
		twitapi = twitter.Api(username=twitter_id, password=twitter_pwd)
		dms = twitapi.GetDirectMessages(since_id=twitter_dm_id)
		#print 'DMs rxed %s' % str(len(dms))
		for dm in dms:
			sender_name = dm.sender_screen_name
			dm_id = dm.id
			txt = dm.text
			
			#print '%s rxed from %s' % (txt, sender_name)
			
			#insert a case
			api.create_case(db=db,
			title=dm.text,
			status=api.get_default_status_id(db),
			priority=api.get_default_priority_id(db),
			created_via='twitter',
			desc = '%s by %s via twitter' % (dm.text, dm.sender_screen_name),
			created_by=uid,
			created_at=request.now,
			last_modified_by=uid,
			last_modified_at=request.now)		
			
			#print 'case created'
			
			#store the id
			db(db.config.id==config_id).update(last_dm_id=dm_id)
			
			#reply back
			reply_msg='@%s Your YATSY Ticket is created' % sender_name
			#print reply_msg
			st=twitapi.PostUpdate(reply_msg)
			#print st.text
		ret_dict=dict(id=0, msg='success')
	except Exception,e:
		ret_dict=dict(id=1,msg=str(e))
	return json.dumps(ret_dict)